package com.tybbank.Activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tybbank.Base.BaseActivity;
import com.tybbank.Bean.MeBean;
import com.tybbank.Bean.YZMBean;
import com.tybbank.Login.LoginActivity;
import com.tybbank.MyApplication;
import com.tybbank.R;
import com.tybbank.Utils.Constant;
import com.tybbank.Utils.MD5Utils;
import com.tybbank.Utils.MyDialogUtils;
import com.tybbank.Utils.logUtilssss;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.Comparator;
import java.util.SortedMap;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2018/9/27 0027.
 */

public class PrograssbarActivity extends BaseActivity {
    @BindView(R.id.toolbar_close)
    ImageButton toolbarClose;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_right)
    TextView toolbarRight;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_dengji)
    TextView tvDengji;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.exit_enter)
    Button exit_enter;
    @BindView(R.id.tv_tuijianren_phone)
    TextView tvTuijianrenPhone;

    private Intent intent;
    private Dialog changeNameDialog;//昵称修改dialog
    private Button cancelButton;
    private Button okButton;
    private EditText pswEdit;//昵称编辑框

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_prograssbar);
        ButterKnife.bind(this);
        toolbar(toolbar, getString(R.string.gerenxinxi), R.mipmap.icon_close);
        init();
    }

    private void init() {
        String time = MD5Utils.getTime();
        SortedMap<String, String> parameters = new TreeMap<String, String>(
                new Comparator<String>() {
                    public int compare(String obj1, String obj2) {
                        // 降序排序
                        return obj1.compareTo(obj2);
                    }
                });
        parameters.put("uuid", MyApplication.uuid);
        parameters.put("token", MyApplication.token);
        parameters.put("TimeStamp", time);
        String sign = MD5Utils.createSign(parameters);
        final Dialog dialog = MyDialogUtils.createLoadingDialog(this, getString(R.string.loading));
        dialog.show();
        OkHttpUtils
                .post()
                .url(Constant.user_detail)
                .addParams("uuid", MyApplication.uuid)
                .addParams("token", MyApplication.token)
                .addParams("TimeStamp", time)
                .addParams("Sign", sign)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                        dialog.dismiss();
                        Toast.makeText(getBaseContext(), getString(R.string.error), Toast.LENGTH_SHORT).show();
                        return;
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        logUtilssss.e("TAG我的" + response.toString());
                        dialog.dismiss();
                        string(response);
                    }

                    private void string(String json) {
                        MeBean enterBean = new Gson().fromJson(json, new TypeToken<MeBean>() {
                        }.getType());
                        int status = enterBean.getCode();
                        if (status == 1011) {
                            tvDengji.setText(enterBean.getUser_detail().getNickname());
                            tvPhone.setText(enterBean.getUser_detail().getAccount());
                            tvTuijianrenPhone.setText(enterBean.getUser_detail().getPid());
                            tvAddress.setText(enterBean.getUser_detail().getAbc_money_path());


                        } else if (status == 1004) {
                            Intent intent = new Intent(getBaseContext(), LoginActivity.class);
                            startActivity(intent);
                            return;
                        } else {
                            Toast.makeText(getBaseContext(), enterBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    @OnClick({R.id.tv_address, R.id.exit_enter})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.tv_address:
                showChangeNameDialog();
                break;
            case R.id.exit_enter:
                AlertDialog.Builder builder = new AlertDialog.Builder(PrograssbarActivity.this);
                builder.setTitle(getString(R.string.tishi));
                builder.setMessage(getString(R.string.tishiyu));
                builder.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //如果不是空 就清空本地临时文件夹
                        MyApplication.token = "";
                        SharedPreferences sp = getSharedPreferences("user", Context.MODE_PRIVATE);
                        if (sp != null) {
                            sp.edit().clear().commit();
                        }
                        Intent intent = new Intent(PrograssbarActivity.this, LoginActivity.class);
                        startActivity(intent);
                        PrograssbarActivity.this.finish();
                    }
                });
                builder.setNegativeButton(getString(R.string.no), null);
                builder.create().show();
                break;
        }
    }

    @Override
    public void LeftClose() {
        super.LeftClose();
        PrograssbarActivity.this.finish();
    }

    private void showChangeNameDialog() {
        if (changeNameDialog == null) {
            changeNameDialog = new Dialog(PrograssbarActivity.this);
            changeNameDialog.setContentView(R.layout.dailog_change_name);
            //设置dialog弹出的位置和大小
            //获取屏幕宽高
            WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
            Display display = wm.getDefaultDisplay();
            int width = display.getWidth();
            int height = display.getHeight();

            Window dialogWindow = changeNameDialog.getWindow();
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            dialogWindow.setGravity(Gravity.CENTER);
            //lp.x与lp.y表示相对于原始位置的偏移.
            //将对话框的大小按屏幕大小的百分比设置
            lp.width = (int) (width * 0.75); // 宽度
            lp.height = (int) (height * 0.35); // 高度

            dialogWindow.setAttributes(lp);

            pswEdit = (EditText) changeNameDialog.findViewById(R.id.FactRstDialogPsw);
            cancelButton = (Button) changeNameDialog.findViewById(R.id.FactRstDialogCancel);
            okButton = (Button) changeNameDialog.findViewById(R.id.FactRstDialogCertain);
            cancelButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View source) {
                    changeNameDialog.dismiss();
                }
            });

            okButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View source) {
                    String pwd = pswEdit.getText().toString();//获取用户填写的昵称
                    if (!TextUtils.isEmpty(pwd)) {
                        submit(pwd);
                        changeNameDialog.dismiss();
                    } else {
                        showTips(getString(R.string.qianbaonull));
                    }
                }
            });

        }

        if (changeNameDialog != null) {
            changeNameDialog.show();
        }
    }

    //提交昵称
    private void submit(final String pwd) {
        String time = MD5Utils.getTime();
        SortedMap<String, String> parameters = new TreeMap<String, String>(
                new Comparator<String>() {
                    public int compare(String obj1, String obj2) {
                        // 降序排序
                        return obj1.compareTo(obj2);
                    }
                });
        parameters.put("token", MyApplication.token);
        parameters.put("uuid", MyApplication.uuid);
        parameters.put("path", pwd);
        parameters.put("TimeStamp", time);
        String sign = MD5Utils.createSign(parameters);

        final Dialog dialog = MyDialogUtils.createLoadingDialog(PrograssbarActivity.this, getString(R.string.loading));
        OkHttpUtils
                .post()
                .url(Constant.abc_path)
                .addParams("token", MyApplication.token)
                .addParams("uuid", MyApplication.uuid)
                .addParams("path", pwd)
                .addParams("TimeStamp", time)
                .addParams("Sign", sign)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                        dialog.dismiss();
                        if (changeNameDialog != null) {
                            changeNameDialog.dismiss();
                        }
                        Toast.makeText(getBaseContext(), getString(R.string.error), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        dialog.dismiss();
                        logUtilssss.e("提交昵称返回数据" + response.toString());
                        try{

                        YZMBean result = new Gson().fromJson(response, YZMBean.class);

                        if (result.getCode() == 1011) {
                            showTips(result.getMsg());
                            if (changeNameDialog != null) {
                                changeNameDialog.dismiss();
                            }
                            tvAddress.setText(pwd);

                        } else if (result.getCode() == 1004) {
                            intent = new Intent(getBaseContext(), LoginActivity.class);
                            startActivity(intent);
                            return;
                        } else {
                            showTips(result.getMsg());
                        }

                        }catch (Exception e){
                            showTips(getString(R.string.error));
                        }
                    }
                });

    }

}
